﻿using System;
using System.Collections.Generic;


namespace IQIGame.Onigao.Framework
{
    /// <summary>
    /// 字典池的情况不常见
    ///<code>
    /// public static class DictionaryPools {
    ///    public static readonly DictionaryPoolImpl《int, int》 guidPool = new DictionaryPoolImpl《int, int》();
    /// }
    /// </code>
    /// </summary>
    public class DictionaryPoolImpl<TKey, TValue>
    {
        private readonly Stack<Dictionary<TKey, TValue>> pool = new Stack<Dictionary<TKey, TValue>>();
        private int _poolSize;

        public DictionaryPoolImpl(int poolSize = 10) {
            this._poolSize = poolSize;
        }

        public int PoolSize {
            get => _poolSize;
            set {
                if (value < 0) throw new ArgumentException();
                _poolSize = value;
            }
        }

        public Dictionary<TKey, TValue> Get() {
            if (pool.Count > 0) {
                return pool.Pop();
            }
            return new Dictionary<TKey, TValue>();
        }

        public void Put(Dictionary<TKey, TValue> obj) {
            if (obj == null) {
                LogGame.LogError("DictionaryPool.Put obj is null");
                return;
            }

            obj.Clear();
            if (pool.Count >= _poolSize)
                return;
            pool.Push(obj);
        }

        public void Clear() {
            pool.Clear();
        }
    }
}